﻿Imports System.Windows
Imports System.Reflection

Public Class SharedResources


    Private Shared _sharedDictionaries As New Dictionary(Of String, WeakReference)

    Public Shared ReadOnly MergedDictionariesProperty As DependencyProperty = DependencyProperty.RegisterAttached("MergedDictionaries", GetType(String), GetType(SharedResources), New FrameworkPropertyMetadata(New PropertyChangedCallback(AddressOf OnMergedDictionariesChanged)))

    Public Shared Function GetMergedDictionaries(ByVal d As DependencyObject) As String
        Return d.GetValue(MergedDictionariesProperty)
    End Function

    Public Sub SetMergedDictionaries(ByVal d As DependencyObject, ByVal value As String)
        d.SetValue(MergedDictionariesProperty, value)
    End Sub

    Private Shared Sub OnMergedDictionariesChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
        If Not String.IsNullOrEmpty(e.NewValue) Then
            For Each dictionaryName As String In e.NewValue.Split(";")
                Dim dictionary As ResourceDictionary = GetResourceDictionary(dictionaryName)
                If Not dictionary Is Nothing Then
                    If d.GetType Is GetType(FrameworkElement) Then
                        CType(d, FrameworkElement).Resources.MergedDictionaries.Add(dictionary)
                    ElseIf d.GetType Is GetType(FrameworkContentElement) Then
                        CType(d, FrameworkContentElement).Resources.MergedDictionaries.Add(dictionary)
                    End If
                End If
            Next
        End If
    End Sub

    Private Shared Function GetResourceDictionary(ByVal dictionaryName As String) As ResourceDictionary
        Dim result As ResourceDictionary = Nothing
        If Not _sharedDictionaries.ContainsKey(dictionaryName) AndAlso _sharedDictionaries(dictionaryName).Target Is Nothing Then


            Dim assemblyName As String = System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().ManifestModule.Name)

            result = Application.LoadComponent(New Uri(String.Format("{0};component/Resources/{1}.xaml", assemblyName, dictionaryName), UriKind.Relative))
            _sharedDictionaries(dictionaryName) = New WeakReference(result)

        End If
        Return result
    End Function




End Class





